import functools
import logging
import datetime

import pandas as pd
from xToolkit import xfile


def get_date():
    current_date = datetime.datetime.now().strftime('%Y-%m-%d')
    return current_date


def write_as_excel(output_file_name, source_info_dict_list, columns_order,
                   columns_rename_map=None, columns_in_percent=None):
    """
    生成excel表
    :param output_file_name: 输出文件名
    :param source_info_dict_list: 待写入数据的字典列表
    :param columns_order: 列名顺序
    :param columns_rename_map: 需要重命名的列名字典
    :param columns_in_percent: 需要转换为百分数的列
    """
    if not source_info_dict_list:
        logging.warning('所传入信息列表没有任何内容，故而无EXCEL文件生成。')
        return 0
    pf = pd.DataFrame(source_info_dict_list)
    # 调整列顺序
    pf = pf[columns_order]
    # 记录需要被转换为百分比的列的字母序号
    alphabet_columns_in_percent = []
    if columns_in_percent:
        for column in columns_in_percent:
            alphabet_columns_in_percent.append(chr(65 + columns_order.index(column)))
    # 重命名列
    if columns_rename_map:
        pf.rename(columns=columns_rename_map, inplace=True)
    pf.fillna(' ', inplace=True)
    # 解除Excel单表URL类型数据量限制（65530）, 将strings_to_urls自动转换功能关闭
    writer = pd.ExcelWriter(output_file_name, engine='xlsxwriter',
                            engine_kwargs={'options': {'strings_to_urls': False}})
    pf.to_excel(writer, encoding='utf-8', index=False)
    # 转换相应列为数字格式的百分比输出
    if columns_in_percent:
        format_obj = writer.book.add_format({'num_format': '0.00%'})
        for alphabet in alphabet_columns_in_percent:
            writer.book.sheetnames['Sheet1'].set_column(f'{alphabet}:{alphabet}', cell_format=format_obj)
    writer.save()
    return len(source_info_dict_list)


def read_excel_to_dict_list(file):
    content = xfile.read(file).excel_to_dict(max=float('inf'))
    if not isinstance(content, list):
        logging.warning(f'所读取的文件{file}不存在，即将返回空列表')
        content = []
    return content


def read_columns_list_from_file(file_name, column_name):
    repo_url_list = []
    repo_info_dict = read_excel_to_dict_list(file_name)
    for record in repo_info_dict:
        repo_url_list.append(record[column_name])
    return repo_url_list


def clock(func):
    @functools.wraps(func)
    def clocked(*args, not_clock_me=False, **kwargs):
        start = datetime.datetime.now()
        result = func(*args, **kwargs)
        end = datetime.datetime.now()
        duration = (end - start).seconds
        stop_at = end.strftime('%Y-%m-%d %X')
        if not not_clock_me:
            formed_dur = str(datetime.timedelta(seconds=duration))
            print(f"时间记录：于{stop_at}执行完毕，耗时{formed_dur}\n")
        return result
    return clocked
